package com.sxhalo.fsms.controller.api;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.FactDepartment;
import com.sxhalo.fsms.export.ExcelUtils;
import com.sxhalo.fsms.export.ExportSetInfo;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.IFactDepartmentService;
import com.sxhalo.fsms.util.ApiResult;
import com.sxhalo.fsms.util.TreeData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/api")
public class DepartmentController extends BaseController {

	@Autowired
	private IFactDepartmentService departmentService;

	@ResponseBody
	@RequestMapping(value = "/department", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult findModule(Integer current, Integer pageSize, HttpServletRequest req) {
		String where = "a.delete_flag=0";
		String order = "";
		if (!isBlank(req.getParameter("departmentName"))) {
			where += " and a.department_name like '%" + req.getParameter("departmentName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("departmentDesc"))) {
			where += " and a.department_desc like '%" + req.getParameter("departmentDesc").trim() + "%'";
		}
		if (!isBlank(req.getParameter("parentName"))) {
			where += " and b .department_name like '%" + req.getParameter("parentName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("useState"))) {
			where += " and a.use_state=" + req.getParameter("useState");
		}
		return findList(current, pageSize, where, order, departmentService);
	}

	@ResponseBody
	@SysControllerLog(operationName = "新增", modelName = "部门管理")
	@RequestMapping(value = "/department", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult saveDepartment(@RequestBody FactDepartment record, String method, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		record.setDeleteFlag(0);
		record.setCreateTime(nowtime);
		departmentService.insertSelective(record);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "编辑", modelName = "部门管理")
	@RequestMapping(value = "/department", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult updateDepartment(@RequestBody FactDepartment record, String method, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		departmentService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "部门管理")
	@RequestMapping(value = "/department", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult delDepartment(Integer departmentId, String method, HttpServletRequest req) {
		FactDepartment record = new FactDepartment();
		record.setDepartmentId(departmentId);
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setDeleteFlag(1);
		record.setUpdateTime(nowtime);
		departmentService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "部门管理")
	@RequestMapping(value = "/department/batchdel", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult batchDelDepartment(String  ids, String method, HttpServletRequest req) {
		departmentService.deleteByWhere(" department_id in ("+ids+")");
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@RequestMapping(value = "/department/tree", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public ApiResult findTree(HttpServletRequest req) {
		List<TreeData> treeData = new ArrayList<>();
		TreeData item = new TreeData();
		item.setTitle("根目录");
		item.setValue("0");
		item.setKey("0");
		item.setChildren(findTreeData(0));
		treeData.add(item);
		return ApiResult.retOK(req, treeData);
	}

	private List<TreeData> findTreeData(Integer parentId) {
		List<TreeData> treeData = new ArrayList<TreeData>();
		List<FactDepartment> list = departmentService
				.findWhereList("delete_flag=0 and use_state=1 and parent_id=" + parentId, "");
		for (FactDepartment department : list) {
			TreeData item = new TreeData();
			item.setTitle(department.getDepartmentName());
			item.setKey(department.getDepartmentId().toString());
			item.setValue(department.getDepartmentId().toString());
			List<TreeData> children = findTreeData(department.getDepartmentId());
			if (children.size() > 0) {
				item.setChildren(children);
			}
			treeData.add(item);
		}
		return treeData;
	}

	// 表头选择
	private List<String[]> createUsersExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "部门名称", "部门描述", "上级部门名称", "是否启用", "创建时间", "更新时间" };
		headlist.add(row1);
		return headlist;
	}

	@ResponseBody
	@SysControllerLog(operationName = "导出", modelName = "部门管理")
	@RequestMapping(value = "/exportDepartmentExcel", method = RequestMethod.GET)
	public void deviceDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "部门列表";
		String[] Userkeys = { "departmentName", "departmentDesc", "parentName", "useState", "createTime",
				"updateTime" };

		String where = "";

		List<FactDepartment> data = departmentService.findPagerList(0, -1, where, "");

		ExportSetInfo info = new ExportSetInfo();
		List<Map<String, Object>> coalSalesList = createUserListRecord(data);
		info.setHeadNames(createUsersExcelHead());
		info.setDatalist(coalSalesList);
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);

	}

	private List<Map<String, Object>> createUserListRecord(List<FactDepartment> data) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (FactDepartment fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("departmentName", fd.getDepartmentName());
			mapValue.put("departmentDesc", fd.getDepartmentDesc());
			mapValue.put("useState", fd.getUseState() == 0 ? "未启用" : "启用");
			mapValue.put("createTime", dateFormat.format(fd.getCreateTime()));
			mapValue.put("updateTime", dateFormat.format(fd.getUpdateTime()));

			listmap.add(mapValue);
		}

		return listmap;
	}
}
